package com.example.android.commitcontent.ime.cores.adapters;

import android.content.Context;
import android.support.annotation.NonNull;

import java.util.List;

/**
 * RecyclerView single selection Adapter
 * Created by xuyougen
 * @param <D> data type
 */
public class BaseSingleChooseAdapter<D> extends BaseRecyclerViewAdapter<D> {

    protected int mCurrentSelectedPosition = -1;
    private int mCheckEventViewId = -1;  //响应选择事件的viewId，默认点击itemView响应单选事件
    private OnItemSelectedListener mOnItemSelectedListener;

    public BaseSingleChooseAdapter(Context context, int layoutRes, List<D> dataList) {
        super(context, layoutRes, dataList);
    }


    public BaseSingleChooseAdapter(Context context, int layoutRes, List<D> dataList, int checkEventViewId) {
        super(context, layoutRes, dataList);
        mCheckEventViewId = checkEventViewId;
    }


    public BaseSingleChooseAdapter(Context context, int layoutRes, List<D> dataList, int checkEventViewId, int defaultSelectedPosition) {
        super(context, layoutRes, dataList);
        mCurrentSelectedPosition = defaultSelectedPosition;
    }

    @Override
    protected void onHolderCreated(@NonNull Holder holder) {
        if (mCheckEventViewId > 0)
            holder.findViewById(mCheckEventViewId).setOnClickListener(v -> setSelectedPosition(holder.getAdapterPosition()));
        else
            holder.itemView.setOnClickListener(v -> setSelectedPosition(holder.getAdapterPosition()));
    }

    public BaseSingleChooseAdapter<D> setSelectedPosition(int position) {
        if (mOnItemSelectedListener != null)
            if (mCurrentSelectedPosition == position) {
                mOnItemSelectedListener.onItemReselected(position);
                return this;
            } else {
                mOnItemSelectedListener.onItemSelected(position);
            }
        mCurrentSelectedPosition = position;
        notifyDataSetChanged();
        return this;
    }

    public int getSelectedPosition() {
        return mCurrentSelectedPosition;
    }

    public BaseSingleChooseAdapter<D> setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
        this.mOnItemSelectedListener = onItemSelectedListener;
        return this;
    }

    public interface OnItemSelectedListener {
        void onItemSelected(int position);

        void onItemReselected(int position);
    }

}
